/**
 * 
 */
package com.ph.agent.api.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ph.base.BaseController;
import com.ph.shopping.common.core.constant.CommonConstants;
import com.ph.shopping.common.core.customenum.ChargeEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.core.customenum.RoleEnum;
import com.ph.shopping.common.core.exception.BizException;
import com.ph.shopping.common.util.com.order.CreateOrderUtil;
import com.ph.shopping.common.util.com.order.OrderBizCode;
import com.ph.shopping.common.util.page.PageBean;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.agent.entity.Agent;
import com.ph.shopping.facade.agent.entity.AgentChargeRecord;
import com.ph.shopping.facade.agent.entity.AgentDrawcashRecord;
import com.ph.shopping.facade.agent.entity.AgentImage;
import com.ph.shopping.facade.agent.service.IAgentImageService;
import com.ph.shopping.facade.agent.service.IAgentService;
import com.ph.shopping.facade.agent.vo.AgentVo;
import com.ph.shopping.facade.agent.vo.UserBalanceRecordVo;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.service.IBankCardBindService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.merchant.entity.UserBalance;
import com.ph.shopping.facade.merchant.service.IMerchantService;
import com.ph.shopping.facade.merchant.vo.UserBalanceVo;
import com.ph.shopping.facade.permission.vo.SessionRoleVo;
import com.ph.shopping.facade.permission.vo.SessionUserVo;
import com.ph.shopping.facade.supplier.service.ISupplierService;
import com.ph.shopping.facade.supplier.vo.SupplierVo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @项目：phshopping-api-platform
 *
 * @描述：
 *
 * @作者： 舒豪
 *
 * @创建时间：2017年3月9日
 *
 * @Copyright @2017 by 舒豪
 */
@Controller
@RequestMapping("api/agent")
public class AgentController extends BaseController{
	
	@Reference(version="1.0.0")
	private IAgentService iAgentService;

	@Reference(version="1.0.0")
	private IAgentImageService iAgentImageService;

	@Reference(version="1.0.0")
	private IMerchantService iMerchantService;

	@Reference(version = "1.0.0")
	private IMemberService iMemberService;

    @Reference(version = "1.0.0")
    private ISupplierService iSupplierService;

    //银行卡绑定接口，用于获取银行卡信息
    @Reference(version = "1.0.0")
    private IBankCardBindService iBankCardBindService;
    
	/**
	 * 跳转代理列表页面
	 * @return
	 */
	@RequestMapping(value="/listPage",method=RequestMethod.GET)
	public String agentListPage(){
		return "/agent/agent/agentList";
	}
	
	/**
	 * 跳转待审核代理列表页面
	 * @return
	 */
	@RequestMapping(value="/pendingAgentPage",method=RequestMethod.GET)
	public String pendingAgentPage(){
		return "/agent/agent/pendingAgentList";
	}
	

	/**
	 * 跳转到新增页面
	 *
	 * @return
	 */
	@RequestMapping(value = "/addAgentPage", method = RequestMethod.GET)
	public String addAgentPage(@ModelAttribute Agent agent) {
		return "/agent/agent/addAgent";
	}

	/**
	 * 下级代理列表页面
	 * @return
	 */
	@RequestMapping(value="/agentSonsPage",method=RequestMethod.GET)
	public Object agentSonsPage(@ModelAttribute Agent agent) {
		try {
			ModelAndView mv = new ModelAndView("/agent/agent/agentSonsList");
			mv.addObject("agent", agent);
			return mv;
		} catch (Exception e) {
			logger.error("获取代理商信息异常:", e.getMessage());
			return "";
		}

	}

	/**
	 * 跳转代理详情页面
	 * @return
	 */
	@RequestMapping(value="/agentDetailPage",method=RequestMethod.GET)
	public Object agentDetailPage(@ModelAttribute Agent agent) {

		//获取session，通过Session获取用户Id作为代理商Id
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//如果角色类型是代理商，设置代理商Id为用户Id去查询供应商详情
			SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
			RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
			if("CITY_AGENT".equals(roleEnum.name())||"COUNTY_AGENT".equals(roleEnum.name())||"COMMUNITY_AGENT".equals(roleEnum.name())){
                if (agent.getId() == null || "".equals(agent.getId())) {
                    agent.setId(sessionUserVo.getId());
                }

			}
		}
		try {
			ModelAndView mv = new ModelAndView("/agent/agent/agentDetail");
			mv.addObject("agent", iAgentService.getAgentDetail(agent));
			return mv;
		} catch (Exception e) {
			logger.error("获取代理商信息异常:", e.getMessage());
			return "";
		}

	}

	/**
	 * 跳转到修改页面
	 * @param agent
	 * @return
	 */
	@RequestMapping(value="/updateAgentPage",method=RequestMethod.GET)
	public Object updateAgentPage(@ModelAttribute Agent agent) {
		try {
			ModelAndView mv = new ModelAndView("/agent/agent/updateAgent");
			AgentVo agentVo= iAgentService.getAgentDetail(agent);
			if (agentVo.getProvinceId() == null) {
				agentVo.setProvinceId("-1");
			}
			if (agentVo.getCityId() == null) {
				agentVo.setCityId("-1");
			}
			if (agentVo.getCountyId() == null) {
				agentVo.setCountyId("-1");
			}
            if (agentVo.getTownId() == null) {
                agentVo.setTownId("0");
            }


			mv.addObject("agent", agentVo);
			return mv;
		} catch (Exception e) {
			logger.error("获取代理商信息异常:", e.getMessage());
			return "";
		}
	}


	/**
	 * 跳转到充值页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/chargeAgentPage", method = RequestMethod.GET)
	public Object chargeAgentPage(@ModelAttribute UserBalanceVo userBalanceVo) {

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/agent/agent/chargeAgentPage");
		
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是代理商，设置代理商Id去查询余额记录，否则为平台下的余额记录
				if("CITY_AGENT".equals(roleEnum.name())||"COUNTY_AGENT".equals(roleEnum.name())||"COMMUNITY_AGENT".equals(roleEnum.name())){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()==null){
				userBalanceVo.setManageId(userBalance.getManageId());
				mv.addObject("userBalanceVo", userBalanceVo);
			}else{
				mv.addObject("userBalanceVo", result.getData());
			}
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取代理商余额异常:", e.getMessage());
			return mv;
		}
		
//		//1.通过代理商Id获取银行卡信息
//		Result result = iBankCardBindService.getBankCardInfo(sessionUserVo.getId(), MemberEnum.PLATFORM_BANK.getCode());
//		BankCardBindInfoDto bankCardBindInfoDto =  (BankCardBindInfoDto) result.getData();
//		if(bankCardBindInfoDto!=null){
//			userBalanceVo.setBankId(bankCardBindInfoDto.getBankId());//绑定id
//			userBalanceVo.setBankName(bankCardBindInfoDto.getBankName());//银行名称
//			userBalanceVo.setBindPhone(bankCardBindInfoDto.getBindPhone());//绑定手机号
//			userBalanceVo.setCardNum(bankCardBindInfoDto.getCardNum());//卡号
//			userBalanceVo.setOwnName(bankCardBindInfoDto.getOwnName());//银行卡所属人
//		}

	}

	/**
	 * 跳转到提现页面
	 * @author 刘颖
	 * @return
	 */
	@RequestMapping(value = "/drawcashAgentPage", method = RequestMethod.GET)
	public Object drawcashAgentPage(@ModelAttribute UserBalanceVo userBalanceVo) throws Exception {

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/agent/agent/drawcashAgentPage");
		
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是代理商，设置代理商Id去查询余额记录，否则为平台下的余额记录
				if("CITY_AGENT".equals(roleEnum.name())||"COUNTY_AGENT".equals(roleEnum.name())||"COMMUNITY_AGENT".equals(roleEnum.name())){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
			
			//查询代理商在余额表是否有数据
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()!=null){
				userBalance = (UserBalance) result.getData();
				userBalanceVo.setBalance(new BigDecimal(userBalance.getBalance()).divide(new BigDecimal("10000"), 2, BigDecimal.ROUND_FLOOR) );
			}else{
				userBalanceVo.setDrawcashMoneyToday(new BigDecimal("10000"));
			}

			userBalanceVo.setManageId(userBalance.getManageId());
			
			//查询当天剩余提现额=10000-当天已提现总额，提现总额不超过1万
			AgentDrawcashRecord agentDrawcashRecord = new AgentDrawcashRecord();
			agentDrawcashRecord.setAgentId(userBalance.getManageId());
			BigDecimal drawcashMoneyToday = iAgentService.getDrawcashMoneyToday(agentDrawcashRecord);
			if(drawcashMoneyToday!=null){
				userBalanceVo.setDrawcashMoneyToday(((new BigDecimal("10000")).subtract(drawcashMoneyToday)).setScale(2,BigDecimal.ROUND_FLOOR));
			}else{
				userBalanceVo.setDrawcashMoneyToday(new BigDecimal("10000"));
			}

			//查询待审核状态的提现总额，待审核提现总额不超过总余额
			agentDrawcashRecord.setStatus(CommonConstants.CHECK_PENDING);
			BigDecimal drawcashStatusPendingTotal = iAgentService.getDrawcashStatusPendingTotal(agentDrawcashRecord);
			if(drawcashStatusPendingTotal!=null){
				userBalanceVo.setDrawcashStatusPendingTotal(drawcashStatusPendingTotal);
			}else{
				userBalanceVo.setDrawcashStatusPendingTotal(new BigDecimal("0"));
			}
			
			//可申请提现的余额
			userBalanceVo.setCanApplyDrawcashMoney(((userBalanceVo.getBalance()).subtract(userBalanceVo.getDrawcashStatusPendingTotal())).setScale(2,BigDecimal.ROUND_FLOOR));
			mv.addObject("userBalanceVo", userBalanceVo);
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取代理商余额异常:", e.getMessage());
			return mv;
		}
		
	}


	/**
	 * 充值的上一步，创建订单，返回订单号
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/chargeAgentCreateOrder",method=RequestMethod.POST)
	public Object chargeAgentCreateOrder(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//1.生成订单号，用于充值记录
		String orderNum = CreateOrderUtil.createOrderCode(OrderBizCode.AGENT_CAHRGE);
		//2.生成充值记录
		AgentChargeRecord agentChargeRecord = new AgentChargeRecord();
		agentChargeRecord.setAgentId(userBalanceVo.getManageId());
		agentChargeRecord.setScore(userBalanceVo.getChargeMoney().multiply(new BigDecimal(10000)));
		agentChargeRecord.setOrderNum(orderNum);
		agentChargeRecord.setChargeType(ChargeEnum.CHARGE_TYPE.getCode());
		agentChargeRecord.setCreater(userBalanceVo.getManageId());
		agentChargeRecord.setCreateTime(new Date());
		iAgentService.addAgentChargeRecord(agentChargeRecord);
		//返回订单号
		return getResult(ResultEnum.SUCCESS,orderNum);
	}


	/**
	 * 提现
	 * @param userBalanceVo
	 * @return
	 * @author 刘颖
	 */
	@ResponseBody
	@RequestMapping(value="/drawcashAgent",method=RequestMethod.POST)
	public Object drawcashAgent(@ModelAttribute("userBalanceVo") UserBalanceVo userBalanceVo) throws Exception  {
		//1.生成订单号，用于提现记录
		String orderNum = CreateOrderUtil.createOrderCode(OrderBizCode.AGENT_DRAW_CASH);
		//写提现表
		AgentDrawcashRecord agentDrawcashRecord = new AgentDrawcashRecord();
		agentDrawcashRecord.setAgentId(userBalanceVo.getManageId());
		agentDrawcashRecord.setScore(userBalanceVo.getDrawcashMoney().multiply(new BigDecimal(10000)));
		agentDrawcashRecord.setStatus(CommonConstants.CHECK_PENDING);//待审核
		agentDrawcashRecord.setDrawcashNo(orderNum);//订单号
		agentDrawcashRecord.setCreateDate(new Date());
		agentDrawcashRecord.setBankName(userBalanceVo.getBankName());
		agentDrawcashRecord.setDrawcashIp("");//这里要设置Ip
		agentDrawcashRecord.setReceiver(userBalanceVo.getOwnName());
		agentDrawcashRecord.setBankNo(userBalanceVo.getCardNum());
		agentDrawcashRecord.setCreater(userBalanceVo.getManageId());
		agentDrawcashRecord.setCreateTime(new Date());
		iAgentService.addAgentDrawcashRecord(agentDrawcashRecord);
		return getResult(ResultEnum.SUCCESS);
	}

	/**
	 *获取代理详情
	 * @param agent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/agentDetail",method= RequestMethod.GET)
	public Object getAgentDetail(Agent agent){
		try {
			return getResult(ResultEnum.SUCCESS, iAgentService.getAgentDetail(agent));
		} catch (Exception e) {
			logger.error("获取代理商信息异常:", e.getMessage());
			return getResult(ResultEnum.DELETE_AGENT_EXCEPTION);
		}

	}

	/**
	 * 分页获取待审核代理
	 * @param page
	 * @param agent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/pendingAgent",method= RequestMethod.GET)
	public Object getPendingAgent(@ModelAttribute PageBean page,@ModelAttribute Agent agent){

        SessionUserVo sessionUserVo = getLoginUser();

        if (sessionUserVo != null && sessionUserVo.getId() != null
                && sessionUserVo.getSessionRoleVo() != null && sessionUserVo.getSessionRoleVo().get(0) != null) {

            //获取角色信息
            SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);

            //判断当前登录者是否是平台
            if (1 == sessionRoleVo.getRoleCode()) {
                //平台获取全部待审核列表
                return iAgentService.getPendingAgent(page, agent);

            }

            //如果该角色为市级代理则获取该区域下的所有代理
            if (3 == sessionRoleVo.getRoleCode()) {
                Agent fAgent = new Agent();
                fAgent.setId(sessionUserVo.getId());
                AgentVo agentVo = iAgentService.getAgentDetail(fAgent);

                //获取区域条件
                Agent agentVoArea = new Agent();
                agentVoArea.setProvinceId(Long.parseLong(agentVo.getProvinceId()));
                agentVoArea.setCityId(Long.parseLong(agentVo.getCityId()));

                //特定获取社区代理和县级代理用5
                agentVoArea.setAgentLevelId(new Long(5));
                Result result = iAgentService.getPendingAgent(page, agentVoArea);
                return result;

            }

        }
        return getResult(ResultEnum.USER_ERROR);
	}

	/**
	 *  分页获取下级代理列表
	 * @param page
	 * @param agent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/agentSons",method= RequestMethod.GET)
	public Object getAgentSons(@ModelAttribute PageBean page,@ModelAttribute Agent agent){
		return iAgentService.getAgentSons(page,agent);
	}

	/**
	 *  分页获取商户列表
	 * @param agent
	 * @return
	 */
	@RequestMapping(value="/merchantListPage",method= RequestMethod.GET)
	public Object getMerchantListPage(@ModelAttribute Agent agent){
		try {
			ModelAndView mv = new ModelAndView("/agent/agent/merchantList");
			mv.addObject("agent", agent);
			return mv;
		} catch (Exception e) {
			logger.error("获取商户信息异常:", e.getMessage());
			return "";
		}
	}


	/**
	 * 分页获取代理列表
	 * @param page
	 * @param agent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/agentList",method=RequestMethod.GET)
	public Object getAgentList(@ModelAttribute PageBean page,@ModelAttribute Agent agent){
        SessionUserVo sessionUserVo = getLoginUser();

        if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){

            //获取角色信息
            SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);

            //判断当前登录者是否是平台
            if (1 == sessionRoleVo.getRoleCode()) {
                //平台全部列表
                return iAgentService.getAgentList(page, agent);

            }

            //判断当前登录者是否是供应商
            if (2 == sessionRoleVo.getRoleCode()) {
                //获取该供应商的详细信息
                SupplierVo supplierVo = new SupplierVo();
                supplierVo.setId(sessionUserVo.getId());
                SupplierVo supplierVoDetail = iSupplierService.getSupplierVoDetail(supplierVo);

                //根据供应商的创建Id返回供应商的代理列表信息
                Agent findAgent = new Agent();
                findAgent.setId(supplierVoDetail.getCreateId());
                return iAgentService.getAgentList(page, findAgent);
            }

            //获取下级代理
            agent.setId(sessionUserVo.getId());
            return iAgentService.getAgentSons(page, agent);
        }
        return getResult(ResultEnum.USER_ERROR);

    }

	
	/**
	 * 跳转余额记录列表页面
	 * @return
	 */
	@RequestMapping(value="/agentBalancePage",method=RequestMethod.GET)
	public Object balanceAgentPage(@ModelAttribute UserBalanceVo userBalanceVo){

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		ModelAndView mv=new ModelAndView("/agent/agent/balanceAgentList");
		try {
			UserBalance userBalance = new UserBalance();
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				
				SessionRoleVo sessionRoleVo = sessionUserVo.getSessionRoleVo().get(0);
				RoleEnum roleEnum = RoleEnum.getRoleEnumByCode(sessionRoleVo.getRoleCode());
				
				//如果角色类型是代理商，设置代理商Id去查询余额记录，否则为平台下的余额记录
				if((roleEnum.equals(RoleEnum.CITY_AGENT)||roleEnum.equals(RoleEnum.COUNTY_AGENT)||roleEnum.equals(RoleEnum.COMMUNITY_AGENT))
						&& (userBalanceVo.getManageId()==null||userBalanceVo.getManageId().equals(""))){
					userBalance.setManageId(sessionUserVo.getId());
				}else{
					userBalance.setManageId(userBalanceVo.getManageId());
				}
			}
			
			//根据ManagerId查询代理商名称
			String agentName = "";
			Agent agent = new Agent();
			agent.setId(userBalance.getManageId());
			AgentVo agentVo = iAgentService.getAgentDetail(agent);
			if(agentVo!=null){
				agentName = agentVo.getAgentName();
			}
			userBalanceVo.setUserName(agentName);
			
			Result result = iMerchantService.getUserBalance(userBalance);
			if(result.getData()==null){
				userBalanceVo.setManageId(userBalance.getManageId());
				userBalanceVo.setBalance(new BigDecimal("0"));
			}else{
				UserBalance userBalance2 = (UserBalance) result.getData();
				userBalanceVo.setManageId(userBalance2.getManageId());
				userBalanceVo.setBalance(new BigDecimal(userBalance2.getBalance()));
			}

			mv.addObject("userBalanceVo", userBalanceVo);
			return mv;
		} catch (BizException e) {
			mv.addObject("userBalanceVo", userBalanceVo);
			logger.error("获取代理商余额异常:", e.getMessage());
			return mv;
		}
	}
	
	/**
	 * 查询代理商余额记录
	 */
	@RequestMapping(value="/agentBalanceList",method=RequestMethod.GET)
	@ResponseBody
	public Object balanceAgent(@ModelAttribute PageBean pagebean,@ModelAttribute UserBalanceRecordVo userBalanceRecordVo){
		try{
			Result result = iAgentService.getUserBalanceRecordVoList(pagebean,userBalanceRecordVo);
			return result;
		}catch(BizException e){
			e.printStackTrace();
			logger.error("获取供应商余额记录异常:", e.getMessage());
			return getResult(ResultEnum.USER_BALANCE_RECORD_EXCEPTION);
		}
	}

	/**
	 * 新增
	 * @param agent
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/add",method=RequestMethod.POST)
	public Object addAgent(@ModelAttribute("agent") Agent agent, HttpServletRequest request){

		//获取图片参数
		String businesslicenseImage = request.getParameter("businesslicenseImage");
		String idCardImage1 = request.getParameter("idCardImage1");
		String idCardImage2 = request.getParameter("idCardImage2");

		List<AgentImage> imageList = new ArrayList<AgentImage>();
		if (businesslicenseImage != null) {
			AgentImage agentImage1 = new AgentImage();
			agentImage1.setType(CommonConstants.BUSINESS_IMAGE_INT_TYPE);
			agentImage1.setSort(CommonConstants.BUSINESS_IMAGE_SORT);//营业执照
			agentImage1.setUrl(businesslicenseImage);
			imageList.add(agentImage1);
			}

		if (idCardImage1 != null) {
			AgentImage agentImage2 = new AgentImage();
			agentImage2.setType(CommonConstants.IDCARD_IMAGE_INT_TYPE);//身份证正面
			agentImage2.setSort(CommonConstants.IDCARD1_IMAGE_SORT);//身份证正面
			agentImage2.setUrl(idCardImage1);
			imageList.add(agentImage2);
			}

		if (idCardImage2 != null) {
			AgentImage agentImage3 = new AgentImage();
			agentImage3.setType(CommonConstants.IDCARD_IMAGE_INT_TYPE);//身份证反面
			agentImage3.setSort(CommonConstants.IDCARD2_IMAGE_SORT);//身份证反面
			agentImage3.setUrl(idCardImage2);
			imageList.add(agentImage3);
		}

		//获取session
		SessionUserVo sessionUserVo = getLoginUser();
		
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//2.设置创建人、 更新人
			agent.setCreateId(sessionUserVo.getId());
			agent.setUpdateId(sessionUserVo.getId());
		}

		agent.setCreateTime(new Date());
		agent.setUpdateTime(new Date());
		agent.setStatus(CommonConstants.CHECK_PENDING);//新增时状态为0，待审核

		// 开始新增
		try {
			logger.debug("代理商新增数据：");
			logger.debug("agent: " + new ObjectMapper().writeValueAsString(agent));
			logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));
            return iAgentService.addAgent(agent, imageList);
        } catch (Exception e) {
			return getResult(ResultEnum.ADD_AGENT_EXCEPTION);
		}
	}

	/**
	 * 通过手机号获取推广师
	 *
	 * @param promoterTel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPromoterByTel", method = RequestMethod.GET)
	public Object getPromoterByTel(String promoterTel) {
		Result memberInfo = iMemberService.getMemberInfoByMobile(promoterTel);
		if (memberInfo != null) {
			Member member = (Member) memberInfo.getData();
			if(member!=null) {
				if (member.getIsMarketing()==Byte.valueOf(CommonConstants.IS_PROMOTER)) {
					return getResult(ResultEnum.SUCCESS, member);
				} else {
					return getResult(ResultEnum.PROMOTER_NON_EXISTENT);
				}
			}else {
				return getResult(ResultEnum.PROMOTER_NON_EXISTENT);
			}
		} else {
			return getResult(ResultEnum.PROMOTER_NON_EXISTENT);
		}
	}


	/**
	 * 修改
	 * @param agent
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public Object updateAgent(@ModelAttribute("agent") Agent agent, HttpServletRequest request){

		logger.info("代理商修改，传入参数：" + agent + "" + request);

		String businesslicenseImage = request.getParameter("businesslicenseImage");
		String idCardImage1 = request.getParameter("idCardImage1");
		String idCardImage2 = request.getParameter("idCardImage2");

		List<AgentImage> imageList = new ArrayList<AgentImage>();
		if (businesslicenseImage != null) {
			AgentImage agentImage1 = new AgentImage();
			agentImage1.setType(CommonConstants.BUSINESS_IMAGE_INT_TYPE);
			agentImage1.setSort(CommonConstants.BUSINESS_IMAGE_SORT);//营业执照
			agentImage1.setUrl(businesslicenseImage);
			imageList.add(agentImage1);
			}

		if (idCardImage1 != null) {
			AgentImage agentImage2 = new AgentImage();
			agentImage2.setType(CommonConstants.IDCARD_IMAGE_INT_TYPE);//身份证正面
			agentImage2.setSort(CommonConstants.IDCARD1_IMAGE_SORT);//身份证正面
			agentImage2.setUrl(idCardImage1);
			imageList.add(agentImage2);
			}

		if (idCardImage2 != null) {
			AgentImage agentImage3 = new AgentImage();
			agentImage3.setType(CommonConstants.IDCARD_IMAGE_INT_TYPE);//身份证反面
			agentImage3.setSort(CommonConstants.IDCARD2_IMAGE_SORT);//身份证反面
			agentImage3.setUrl(idCardImage2);
			imageList.add(agentImage3);
		}

        //获取session
		SessionUserVo sessionUserVo = getLoginUser();
		if(sessionUserVo!=null&&sessionUserVo.getId()!=null
				&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
			//2.设置创建人、 更新人
			agent.setUpdateId(sessionUserVo.getId());
		}
		agent.setUpdateTime(new Date());

		// 开始修改
		try {
			logger.debug("代理商修改数据：");
			logger.debug("agent: " + new ObjectMapper().writeValueAsString(agent));
			logger.debug("imageList: " + new ObjectMapper().writeValueAsString(imageList));
            return iAgentService.updateAgent(agent, imageList);
        } catch (Exception e) {
			return getResult(ResultEnum.UPDATE_AGENT_EXCEPTION);
        }

	}
	
	/**
	 * 修改状态
	 * @param agent
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/updateStatus",method=RequestMethod.POST)
	public Object updateAgentStatus(Agent agent, HttpServletRequest request){
		try{
			//获取session
			SessionUserVo sessionUserVo = getLoginUser();
			//设置 更新人
			if(sessionUserVo!=null&&sessionUserVo.getId()!=null
					&&sessionUserVo.getSessionRoleVo()!=null&&sessionUserVo.getSessionRoleVo().get(0)!=null){
				agent.setUpdateId(sessionUserVo.getId());
			}
			//设置 更新时间
			agent.setUpdateTime(new Date());
			
	    	if(agent.getStatus()==3){
	    		//1.清空登录session
	    		sessionUserVo.getId();
				request.getSession().removeAttribute(agent.getPersonTel());
	    	}
            return iAgentService.updateAgentStatus(agent);
        }catch(BizException e){
			e.printStackTrace();
			return getResult(ResultEnum.CONGEALYES_AGENT_EXCEPTION);//返回短信发送失败的异常
		}
	}



	/**
	 * 删除
	 * @param agent
	 * @return
	 */
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public Object deleteAgent(Agent agent){
		return iAgentService.deleteAgent(agent);
	}



}
